#include <stdio.h>
#include <stdlib.h>
#include "include/libcal-character.h"
#define DB_PATH "/share/calatisiad-project/calatisiad-linux/output/database/characters"
typedef struct libcal_character_object{
	void* sqlite_wrapper;
} libcal_character_object;

void* libcal_create_object(){
	libcal_character_object *obj = (libcal_character_object*) malloc (sizeof(libcal_character_object));
	obj->sqlite_wrapper = (void*) sqlite3_wrapper_create_object(DB_PATH);
	return obj;
}

int libcal_destroy_object(void* object){
	libcal_character_object *obj = (libcal_character_object*) object;
	sqlite3_wrapper_close(obj->sqlite_wrapper);
	free(obj);
}

int character_length(void *object){
	libcal_character_object *obj = (libcal_character_object*)object;
	GString* query;
	GSList* list;

	query = g_string_new( "select count(*) as columncount from character");
	list=(GSList*)sqlite3_wrapper_execute_get(obj->sqlite_wrapper, query->str);

	int ret=-1;

	int len = g_slist_length(list);
	if(len == 2){
		GString* det = (GString*) g_slist_nth_data(list, 1);
		g_slist_free(list);
		sscanf(det->str, "%d", &ret);
		g_string_free(det, TRUE);
	} else {
		g_slist_free(list);
	}
	return ret;


}

GString* character_get_name(void* object, int id){
	libcal_character_object *obj = (libcal_character_object*)object;
	GSList* list;
	GString* query;
       
	if(id > 0) {
		query = g_string_new( "select name from character where id=");
	} else {
		return NULL;
	}
	
	char conv[100];
	sprintf(conv, "%d", id);
	query = g_string_append(query, conv); 

	list=(GSList*)sqlite3_wrapper_execute_get(obj->sqlite_wrapper, query->str);

	int len = g_slist_length(list);
	if(len == 2){
		GString* det = (GString*) g_slist_nth_data(list, 1);
		g_slist_free(list);
		return det;
	} else {
		g_slist_free(list);
		return NULL;
	}
}
GString* character_get_class(void* object, int id){
	libcal_character_object *obj = (libcal_character_object*)object;
	GSList* list;
	GString* query = g_string_new( "select class from character where id=");
	
	char conv[100];
	sprintf(conv, "%d", id);
	query = g_string_append(query, conv); 

	list=(GSList*)sqlite3_wrapper_execute_get(obj->sqlite_wrapper, query->str);

	int len = g_slist_length(list);
	if(len == 2){
		GString* det = (GString*) g_slist_nth_data(list, 1);
		g_slist_free(list);
		return det;
	} else {
		g_slist_free(list);
		return NULL;
	}
}
int character_get_age(void* object, int id){
	libcal_character_object *obj = (libcal_character_object*)object;
	GSList* list;
	GString* query = g_string_new( "select age from character where id=");
	
	char conv[100];
	sprintf(conv, "%d", id);
	query = g_string_append(query, conv); 

	list=(GSList*)sqlite3_wrapper_execute_get(obj->sqlite_wrapper, query->str);

	int len = g_slist_length(list);
	int ret = FALSE;
	if(len == 2){
		GString* det = (GString*) g_slist_nth_data(list, 1);
		sscanf(det->str, "%d", &ret);
		g_slist_free(list);
		g_string_free(det, TRUE);
	}
	
	return ret;
}

